# -*- coding: utf-8 -*-
from apps.log import Logger
from apps import configs


class AlarmModel(object):
    def __init__(self, db):
        self.db = db
        self.table_name = '%salarm' % configs.TABLE_NAME_PREFIX

    async def add_alarm(self, uuid, almtype, almsummary, user_id, device_uuid):
        sql = 'INSERT INTO {0} (uuid, almtype, almsummary, user_id, device_uuid) VALUES(%s,%s,%s,%s,%s)'.format(
            self.table_name)
        return await self.db.execute(
            sql, (uuid, almtype, almsummary, user_id, device_uuid))

    async def get_alarms(self, userid, page: int = 1, limit: int = 15, almtype: int = 0, query=''):
        page = (page - 1) * limit

        if int(almtype) != 0:
            almtype = 'AND almtype="{}"'.format(almtype)
        else:
            almtype = ''

        if query:
            query = 'AND sn="{0}" or device_uuid = "{0}" or name = "{0}"'.format(
                query)
        else:
            query = ''

        sql = '''SELECT t.id,t.uuid,t.almcode,t.almtype,t.almsummary,t.alm_time,t.user_id,t.device_uuid,
        d.id,d.sn,d.name,d.add_time
         FROM {0} AS t INNER JOIN {3}device as d ON t.device_uuid = d.uuid {2} JOIN (SELECT id FROM {0} WHERE user_id ="%s"
         {1} ORDER BY alm_time DESC LIMIT %s, %s ) tmp ON t.id = tmp.id'''.format(
            self.table_name, almtype, query, configs.TABLE_NAME_PREFIX)

        return await self.db.fetchall(sql, (userid, page, limit))
